package com.cmcc.cmii.smsmail.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cmcc.cmii.common.enums.DeleteFlagEnum;
import com.cmcc.cmii.common.enums.IsStopedEnum;
import com.cmcc.cmii.common.utils.JsonUtil;
import com.cmcc.cmii.smsmail.constants.MailMqConstants;
import com.cmcc.cmii.smsmail.dto.ExcepMsgDto;
import com.cmcc.cmii.smsmail.dto.SuccessMsgDto;
import com.cmcc.cmii.smsmail.entity.MailBaseInfo;
import com.cmcc.cmii.smsmail.mapper.MailBaseInfoMapper;
import com.cmcc.cmii.smsmail.model.v1.FileMail;
import com.cmcc.cmii.smsmail.model.v1.HtmlMail;
import com.cmcc.cmii.smsmail.model.v1.ResourceMail;
import com.cmcc.cmii.smsmail.model.v1.SimpleMail;
import com.cmcc.cmii.smsmail.service.IEmailService;
import com.cmcc.cmii.smsmail.utils.MailUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.activation.URLDataSource;
import javax.mail.internet.MimeMessage;
import javax.validation.constraints.NotEmpty;
import java.net.CookieHandler;
import java.net.URL;
import java.util.List;
import java.util.Map;


/**
 * @author Thanks
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@SuppressWarnings("all")
public class EmailServiceImpl implements IEmailService {

    private final MailBaseInfoMapper mailBaseInfoMapper;

    private final RabbitTemplate rabbitTemplate;

    /**
     * 发送简单邮件
     * @param simpleMail
     */
    @Override
    public void sendSimpleMail(SimpleMail simpleMail) {
        try {
            Integer mailType = simpleMail.getMailType();
            MailBaseInfo mailBaseInfo = mailBaseInfoMapper.selectOne(new QueryWrapper<>(MailBaseInfo.builder()
                    .mailType(mailType).deleteFlag(DeleteFlagEnum.NORMAL.getCode())
                    .isStoped(IsStopedEnum.NORMAL.getCode()).build()));
            JavaMailSenderImpl mailSender = MailUtil.createMailSender(mailBaseInfo, simpleMail);
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(simpleMail.getMailFrom());
            message.setSubject(simpleMail.getSubject());
            message.setText(simpleMail.getContent());
            List<String> listMailTo = simpleMail.getListMailTo();
            //发送邮件
            //主送
            message.setTo(listMailTo.toArray(new String[listMailTo.size()]));
            //抄送
            if(!CollectionUtils.isEmpty(simpleMail.getListCopyTo())){
                List<String> listCopyTo = simpleMail.getListCopyTo();
                message.setCc(listCopyTo.toArray(new String[listCopyTo.size()]));
            }
            //密送
            if(!CollectionUtils.isEmpty(simpleMail.getListBlindCopyTo())){
                List<String> listBlindCopyTo = simpleMail.getListBlindCopyTo();
                message.setBcc(listBlindCopyTo.toArray(new String[listBlindCopyTo.size()]));
            }
            //发送
            mailSender.send(message);
            /*for (String mailTo : listMailTo) {
                try {
                    message.setTo(mailTo);
                    mailSender.send(message);
                    //发送成功
                    sendSuccess(simpleMail,"发送成功!");
                } catch (Exception e) {
                    e.printStackTrace();
                    //发送失败
                    sendFail(simpleMail,e);
                }
            }*/
            sendSuccess(simpleMail,"简单邮件发送成功！");
        }catch (Exception e){
            e.printStackTrace();
            sendFail(simpleMail,e,"简单邮件发送失败!");
        }



    }

    /**
     * 发送html邮件
     * @param htmlMail
     */
    @Override
    public void sendHtmlMail(HtmlMail htmlMail) {
        try{
            Integer mailType = htmlMail.getMailType();
            MailBaseInfo mailBaseInfo = mailBaseInfoMapper.selectOne(new QueryWrapper<>(MailBaseInfo.builder()
                    .mailType(mailType).deleteFlag(DeleteFlagEnum.NORMAL.getCode())
                    .isStoped(IsStopedEnum.NORMAL.getCode()).build()));
            JavaMailSenderImpl mailSender = MailUtil.createMailSender(mailBaseInfo, htmlMail);
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(htmlMail.getMailFrom());
            helper.setSubject(htmlMail.getSubject());
            helper.setText(htmlMail.getContent(),Boolean.TRUE);
            //主送
           List<String> listMailTo = htmlMail.getListMailTo();
           helper.setTo(listMailTo.toArray(new String[listMailTo.size()]));
           //抄送
            if(!CollectionUtils.isEmpty(htmlMail.getListCopyTo())){
                List<String> listCopyTo = htmlMail.getListCopyTo();
                helper.setCc(listCopyTo.toArray(new String[listCopyTo.size()]));
            }
            //密送
            if(!CollectionUtils.isEmpty(htmlMail.getListBlindCopyTo())){
                List<String> listBlindCopyTo = htmlMail.getListBlindCopyTo();
                helper.setBcc(listBlindCopyTo.toArray(new String[listBlindCopyTo.size()]));
            }

            mailSender.send(mimeMessage);
            sendSuccess(htmlMail,"html邮件发送成功!");
        }catch (Exception e){
            e.printStackTrace();
            sendFail(htmlMail,e,"html邮件发送失败!");
        }


    }

    @Override
    public void sendFileMail(FileMail fileMail) {
        try{
            Integer mailType = fileMail.getMailType();
            MailBaseInfo mailBaseInfo = mailBaseInfoMapper.selectOne(new QueryWrapper<>(MailBaseInfo.builder()
                    .mailType(mailType).deleteFlag(DeleteFlagEnum.NORMAL.getCode())
                    .isStoped(IsStopedEnum.NORMAL.getCode()).build()));
            JavaMailSenderImpl mailSender = MailUtil.createMailSender(mailBaseInfo, fileMail);
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(fileMail.getMailFrom());
            helper.setSubject(fileMail.getSubject());
            if(StringUtils.isNotBlank(fileMail.getContent())){
                helper.setText(fileMail.getContent(),Boolean.TRUE);
            }

            //主送
            List<String> listMailTo = fileMail.getListMailTo();
            helper.setTo(listMailTo.toArray(new String[listMailTo.size()]));
            //抄送
            if(!CollectionUtils.isEmpty(fileMail.getListCopyTo())){
                List<String> listCopyTo = fileMail.getListCopyTo();
                helper.setCc(listCopyTo.toArray(new String[listCopyTo.size()]));
            }
            //密送
            if(!CollectionUtils.isEmpty(fileMail.getListBlindCopyTo())){
                List<String> listBlindCopyTo = fileMail.getListBlindCopyTo();
                helper.setBcc(listBlindCopyTo.toArray(new String[listBlindCopyTo.size()]));
            }
            //设置附件
            if(!CollectionUtils.isEmpty(fileMail.getFileInfoMap())){
                Map<String, String> fileInfoMap = fileMail.getFileInfoMap();
                fileInfoMap.forEach((k,v)->{
                    try{
                        URLDataSource uds=new URLDataSource(new URL(v));
                        helper.addAttachment(k,uds);
                    }catch (Exception e){
                        e.printStackTrace();
                        sendFail(fileMail,e,"附件下载失败,请检查附件地址是佛正确!");
                        return;
                    }

                });
            }
            //发送邮件
            mailSender.send(mimeMessage);
            //发送成功
            sendSuccess(fileMail,"附件邮件发送成功!");
        }catch (Exception e){
            e.printStackTrace();
            sendFail(fileMail,e,"附件邮件发送失败!");
        }

    }

    @Override
    public void sendStaticResourceMail(ResourceMail resourceMail) {
        try{
            Integer mailType = resourceMail.getMailType();
            MailBaseInfo mailBaseInfo = mailBaseInfoMapper.selectOne(new QueryWrapper<>(MailBaseInfo.builder()
                    .mailType(mailType).deleteFlag(DeleteFlagEnum.NORMAL.getCode())
                    .isStoped(IsStopedEnum.NORMAL.getCode()).build()));
            JavaMailSenderImpl mailSender = MailUtil.createMailSender(mailBaseInfo, resourceMail);
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(resourceMail.getMailFrom());
            helper.setSubject(resourceMail.getSubject());
            if(StringUtils.isNotBlank(resourceMail.getContent())){
                helper.setText(resourceMail.getContent(),Boolean.TRUE);
            }
            //主送
            List<String> listMailTo = resourceMail.getListMailTo();
            helper.setTo(listMailTo.toArray(new String[listMailTo.size()]));
            //抄送
            if(!CollectionUtils.isEmpty(resourceMail.getListCopyTo())){
                List<String> listCopyTo = resourceMail.getListCopyTo();
                helper.setCc(listCopyTo.toArray(new String[listCopyTo.size()]));
            }
            //密送
            if(!CollectionUtils.isEmpty(resourceMail.getListBlindCopyTo())){
                List<String> listBlindCopyTo = resourceMail.getListBlindCopyTo();
                helper.setBcc(listBlindCopyTo.toArray(new String[listBlindCopyTo.size()]));
            }
            //添加图片
            if(!CollectionUtils.isEmpty(resourceMail.getFileInfoMap())){
                Map<String, String> fileInfoMap = resourceMail.getFileInfoMap();
                fileInfoMap.forEach((k,v)->{
                    try{
                        URLDataSource uds=new URLDataSource(new URL(v));
                        helper.addInline(k,uds);
                    }catch (Exception e){
                        e.printStackTrace();
                        sendFail(resourceMail,e,"resource邮件发送失败,请检查地址的正确性!");
                        return;
                    }

                });

            }
            //发送邮件
            mailSender.send(mimeMessage);
            //发送成功
            sendSuccess(resourceMail,"resource邮件发送成功!");

        }catch (Exception e){
            e.printStackTrace();
            sendFail(resourceMail,e,"resource邮件发送失败!");
        }
    }

    /**
     * 发送失败
     * @param data
     * @param e
     */
    private void sendFail(Object data,Exception e,String msg){
        ExcepMsgDto excepMsgDto = new ExcepMsgDto();
        excepMsgDto.setData(data);
        excepMsgDto.setException(e);
        excepMsgDto.setMsg(msg);
        rabbitTemplate.convertAndSend(MailMqConstants.MAIL_SEND_FAIL_EXCHANGE,MailMqConstants.MAIL_SEND_FAIL_KEY,JsonUtil.toJSONString(excepMsgDto));
    }

    /**
     * 发送成功
     * @param data
     * @param msg
     */
    private void sendSuccess(Object data,Object msg){
        SuccessMsgDto successMsgDto = new SuccessMsgDto();
        successMsgDto.setData(data);
        successMsgDto.setMsg(msg);
        rabbitTemplate.convertAndSend(MailMqConstants.MAIL_SEND_SUCCESS_EXCHANGE,MailMqConstants.MAIL_SEND_SUCCESS_KEY, JsonUtil.toJSONString(successMsgDto));
    }

}
